//
//  TEA_VideoViewController.swift
//  NewsItem
//
//  Created by mac on 2023/8/3.
//  Copyright © 2023 Kaka. All rights reserved.
//

import UIKit
import AgoraRtmKit
import AgoraRtcKit
import AVFoundation
import Kingfisher

class TEA_VideoViewController: UIViewController,NaviBarHidden {
    
    var localView = UIView.init(frame: .zero)
    var remoteView = UIView.init(frame: .zero)
    let cancelB = UIButton.initV(img: "hangup")
    
    let backV = UIView.init(frame: .zero)
    let img = UIImageView.initImgView(img: "avarB")
    let cancelB1 = UIButton.initV(img: "hangup")
    let acceptB1 = UIButton.initV(img: "accept")
    private var nameL = UILabel.initV(.setTypeFace(20.Fit, type: .extraBold), text: "", textColor: .color(hexString: "#1D0B00",alpha: 1))
    private var tipL = UILabel.initV(.setTypeFace(18, type: .bold), text: "Incoming Call…", textColor: mainColor)

    private var callNameL = UILabel.initV(.setTypeFace(18, type: .bold), text: "", textColor: .color(hexString: "#FFFFFF",alpha: 1))
    private var callTimeL = UILabel.initV(.setTypeFace(16, type: .bold), text: "", textColor: .color(hexString: "#FFFFFF",alpha: 1))

    var localInvitation:AgoraRtmLocalInvitation?
    var remoteInvitation:AgoraRtmRemoteInvitation?
    var agoraKit:AgoraRtcEngineKit?
    var audioPlayer:AVAudioPlayer?
    var isRecept = false
    var peerStr:String!
    var headImage: UIImage!
    var nameStr:String!
    var timer:Timer?
    var timeCount = 0
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        stopPlayRing()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let ringPath =  Bundle.main.path(forResource: "Voice_Calling", ofType: ".mp3")
        self.startPlayRing(ringPath)
    }

    func startPlayRing(_ ringPath: String?) {
        if ringPath != nil {
            if (audioPlayer != nil) {
                stopPlayRing()
            }
            //在音频播放前首先创建一个异常捕捉语句
            let url = NSURL.fileURL(withPath: ringPath!)
            audioPlayer = try? AVAudioPlayer(contentsOf:url)
            //设置音频对象播放的音量的大小
            audioPlayer?.volume = 1.0
            //设置音频播放的次数，-1为无限循环播放
            audioPlayer?.numberOfLoops = -1
            audioPlayer?.play()
        }
    }
    
    
    func stopPlayRing() {
        if (audioPlayer != nil) {
            audioPlayer?.stop()
            audioPlayer = nil
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.initializeAgoraEngine()
        AgoraRTMClient.shared._kit?.getRtmCall()?.callDelegate = self
        
        self.view.subviews {
            remoteView
            localView
            callNameL
            callTimeL
            cancelB
            backV.subviews {
                img
                nameL
                tipL
                cancelB1
                acceptB1
            }
        }
        
        remoteView.fillContainer()
        localView.width(108.Fit).height(159.Fit).right(5.Fit).top(20.Fit + StatusBarHeight)
        localView.setAllCorners(corner: 10.Fit)
        cancelB.size(70.Fit).bottom(75.Fit)
        cancelB.CenterX == remoteView.CenterX
        
        callNameL.left(20.Fit).top(20.Fit + StatusBarHeight).height(25.Fit)
        callNameL.width(200.Fit)
        
        callTimeL.left(20.Fit).height(20.Fit)
        callTimeL.width(200.Fit)
        callTimeL.Top == callNameL.Bottom + 15.Fit
        
        cancelB.addAct {
            self.agoraKit?.leaveChannel(nil)
            AgoraRtcEngineKit.destroy()
            if self.localInvitation != nil {
                AgoraRTMClient.shared._kit?.getRtmCall()?.cancel(self.localInvitation!, completion: nil)
            }else{
                AgoraRTMClient.shared._kit?.getRtmCall()?.refuse(self.remoteInvitation!, completion: nil)
            }
            
            self.postNotifaction()
            self.navigationController?.popViewController(animated: true)
        }
        
        backV.backgroundColor = .color(hexString: "#F8FAF8")
        backV.fillContainer()
        img.size(175.Fit).top(167.Fit)
        img.CenterX == backV.CenterX
        img.setAllCorners(corner: (175/2).Fit)
        
        nameL.left(10.Fit).right(10.Fit).height(25.Fit)
        nameL.textAlignment = .center
        nameL.Top == img.Bottom + 25.Fit
        
        tipL.left(10.Fit).right(10.Fit).height(25.Fit)
        tipL.textAlignment = .center
        tipL.Top == nameL.Bottom + 5.Fit
        
        if isRecept {
            
            // 接收方
            cancelB1.left(67.5.Fit).size(70.Fit).bottom(100.Fit)
            acceptB1.right(67.5.Fit).size(70.Fit).bottom(100.Fit)
            let dict = self.getDictionaryFromJSONString(jsonString: self.remoteInvitation?.content ?? "")
            if let url = URL(string: dict["headImg"] as! String){
                self.img.kf.setImage(with: url)
            }
            let name = dict["name"] as! String
            self.nameL.text = name
            self.callNameL.text = name
            
        }else
        {
            acceptB1.isHidden = true
            if self.headImage != nil{
                self.img.image = self.headImage
            }
            self.nameL.text = self.nameStr
            self.callNameL.text = self.nameStr
            cancelB1.size(70.Fit).bottom(100.Fit)
            cancelB1.CenterX == backV.CenterX
            self.localInvitation = AgoraRtmLocalInvitation(calleeId: peerStr)
            let dict = ["name":USEINFOMODEL.name,"headImg":USEINFOMODEL.headImage]
            self.localInvitation?.content = dict.toJsonString
            self.localInvitation?.channelId = "10086"
            AgoraRTMClient.shared._kit?.queryPeersOnlineStatus([peerStr], completion: { arr, code in
                print("queryPeersOnlineStatus==-----    ")
                print(arr)
            })
            AgoraRTMClient.shared._kit?.getRtmCall()?.send(self.localInvitation!, completion: { (code) in
                if code == .ok{
                    print(self.peerStr)
                    print("sendSUccess===------         ")
                }
            })
        }
        
       acceptB1.addAct {
            AgoraRTMClient.shared._kit?.getRtmCall()?.accept(self.remoteInvitation!, completion: { (code) in
                self.agoraKit?.joinChannel(byToken: nil, channelId: "10086", info: nil, uid: 0, joinSuccess: { (channel, uid, elapsed) in
                    self.setupLocalVideo()
                    self.stopPlayRing()
                })
            })
        }
        cancelB1.addAct {
            self.agoraKit?.leaveChannel(nil)
            AgoraRtcEngineKit.destroy()
            if self.localInvitation != nil {
                AgoraRTMClient.shared._kit?.getRtmCall()?.cancel(self.localInvitation!, completion: nil)
            }else{
                AgoraRTMClient.shared._kit?.getRtmCall()?.refuse(self.remoteInvitation!, completion: nil)
            }
            self.postNotifaction()
            self.navigationController?.popViewController(animated: true)
        }
    }

    @objc func tick() {
        timeCount = timeCount + 1
        let time = self.secondsToHoursMinutesSeconds(timeCount)
        self.callTimeL.text = String(format: "%.2i:%.2i:%.2i", time.0,time.1,time.2)
    }
    
    func secondsToHoursMinutesSeconds(_ seconds: Int) -> (Int, Int, Int) {
        return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
    }
    
    func initializeAgoraEngine() -> Void {
        self.agoraKit = AgoraRtcEngineKit.sharedEngine(withAppId:"126413953d0447a698c4bca7086d970f", delegate: self)
        self.agoraKit?.setChannelProfile(.communication)
        self.agoraKit?.enableAudio()
        self.agoraKit?.enableLocalAudio(true)
        self.agoraKit?.enableWebSdkInteroperability(true)
        self.agoraKit?.setClientRole(.broadcaster)
        self.agoraKit?.setVideoEncoderConfiguration(AgoraVideoEncoderConfiguration(size: CGSize(width: 1280.0, height: 720.0), frameRate: AgoraVideoFrameRate.fps30, bitrate: AgoraVideoBitrateStandard, orientationMode: AgoraVideoOutputOrientationMode.fixedPortrait, mirrorMode: .auto))
        self.agoraKit?.setDefaultAudioRouteToSpeakerphone(true)
    }
    
    func setupLocalVideo() -> Void {
        self.agoraKit?.enableVideo()
        self.agoraKit?.enableAudio()
        self.agoraKit?.enableLocalAudio(true)
        let videoCanvas = AgoraRtcVideoCanvas()
        videoCanvas.uid = 0
        videoCanvas.renderMode = .hidden
        videoCanvas.view = self.localView
        self.agoraKit?.setupLocalVideo(videoCanvas)
        
    }
    func joinChannel() -> Void {
        self.agoraKit?.joinChannel(byToken: nil, channelId: "10086", info: nil, uid: 0, joinSuccess: { (channel, uid, elapsed) in
            self.stopPlayRing()
            self.setupLocalVideo()
        })
    }
    
    func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{
        let jsonData:Data = jsonString.data(using: .utf8)!
        let dict = try?JSONSerialization.jsonObject(with:jsonData,options: .mutableContainers)
        if dict != nil {
            return dict as!NSDictionary
        }
        return NSDictionary()
    }
    func postNotifaction() -> Void {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeDelegate"), object: nil, userInfo: nil)
    }
    
}


extension TEA_VideoViewController:AgoraRtcEngineDelegate,AgoraRtmCallDelegate{
    
    func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinedOfUid uid: UInt, elapsed: Int) {
        self.backV.isHidden = true
        let videoCanvas = AgoraRtcVideoCanvas()
        videoCanvas.uid = uid
        videoCanvas.renderMode = .hidden
        videoCanvas.view = self.remoteView
        self.agoraKit?.setupRemoteVideo(videoCanvas)
        timer = Timer.scheduledTimer(timeInterval: 1,
                                     target: self,
                                     selector: #selector(tick),
                                     userInfo: nil,
                                     repeats: true)
    }
    
    // 被叫对的
    func rtcEngine(_ engine: AgoraRtcEngineKit, firstRemoteVideoDecodedOfUid uid: UInt, size: CGSize, elapsed: Int) {
        self.backV.isHidden = true
        let videoCanvas = AgoraRtcVideoCanvas()
        videoCanvas.uid = uid
        videoCanvas.renderMode = .hidden
        videoCanvas.view = self.remoteView
        self.agoraKit?.setupRemoteVideo(videoCanvas)
        timer = Timer.scheduledTimer(timeInterval: 1,
                                     target: self,
                                     selector: #selector(tick),
                                     userInfo: nil,
                                     repeats: true)

    }
    
    func rtcEngine(_ engine: AgoraRtcEngineKit, didOfflineOfUid uid: UInt, reason: AgoraUserOfflineReason) {
        self.agoraKit?.leaveChannel(nil)
        AgoraRtcEngineKit.destroy()
        self.postNotifaction()
        self.navigationController?.popViewController(animated: true)
    }
        
    func rtcEngine(_ engine: AgoraRtcEngineKit, remoteVideoStateChangedOfUid uid: UInt, state: AgoraVideoRemoteState) {
        print(state.rawValue)
        print("remoteVideoStateChangedOfUid=-------    ")
        if state == .stopped {
            self.agoraKit?.leaveChannel(nil)
            AgoraRtcEngineKit.destroy()
            self.postNotifaction()
            self.navigationController?.popViewController(animated: true)
        }
    }
        
    func rtmCallKit(_ callKit: AgoraRtmCallKit, localInvitationAccepted localInvitation: AgoraRtmLocalInvitation, withResponse response: String?) {
//        self.backV.isHidden = true
        self.joinChannel()
    }
      
    func rtmCallKit(_ callKit: AgoraRtmCallKit, localInvitationRefused localInvitation: AgoraRtmLocalInvitation, withResponse response: String?) {
        self.postNotifaction()
        self.navigationController?.popViewController(animated: true)
    }
        
    // 被叫
    func rtmCallKit(_ callKit: AgoraRtmCallKit, remoteInvitationCanceled remoteInvitation: AgoraRtmRemoteInvitation) {
        self.postNotifaction()
        self.navigationController?.popViewController(animated: true)
    }
    
    func rtmCallKit(_ callKit: AgoraRtmCallKit, remoteInvitationRefused remoteInvitation: AgoraRtmRemoteInvitation) {
        self.postNotifaction()
        self.navigationController?.popViewController(animated: true)
    }

    func rtmCallKit(_ callKit: AgoraRtmCallKit, remoteInvitationAccepted remoteInvitation: AgoraRtmRemoteInvitation) {
        
    }

    func rtmCallKit(_ callKit: AgoraRtmCallKit, remoteInvitationFailure remoteInvitation: AgoraRtmRemoteInvitation, errorCode: AgoraRtmRemoteInvitationErrorCode) {
        
    }
}
